import { constantRoutes } from '@/router' // 初始路由表，里面包含登录和404页面路由

// 后端返回的嵌套路由表(也就是最开始说的"第一种后端返回的路由表格式")转一维数组（也就是最开始说的"第二种后端返回的路由表格式"），
// 转换后用于与总路由表进行比较，后端若返回一维数组则直接交由下面filterAsyncRoutes处理
function MultidimensionalToOnedimensional(routesMap) {
  const filterRoutesMap = []
  !(function fn(routesMap) {
    routesMap.forEach(route => {
      const tmp = {}
      for (const key in route) {
        if (Object.hasOwnProperty.call(route, key)) {
          if (key !== 'children') {
            tmp[key] = route[key]
          } else if (key === 'children') {
            fn(route[key])
          }
        }
      }
      filterRoutesMap.push(tmp)
    })
  }(routesMap))
  return filterRoutesMap
}

// 比对过滤路由表，生成最终可访问的路由表
export function filterAsyncRoutes(routes, filterRoutesMap) {
  const accessedRoutes = []
  routes.forEach(route => {
    const tmp = {}
    if (filterRoutesMap.some(a => a.path == route.path)) {
      for (const key in route) {
        if (Object.hasOwnProperty.call(route, key)) {
          if (key !== 'children') {
            tmp[key] = route[key]
          } else if (key === 'children') {
            const tmpC = filterAsyncRoutes(route[key], filterRoutesMap);
            (tmpC.length > 0) && (tmp.children = tmpC)
          }
        }
      }
    }
    tmp.path && accessedRoutes.push(tmp)
  })

  return accessedRoutes
}

const getButtons = filterRoutesMap => {
  const res = []
  filterRoutesMap.forEach(item => {
    const { path } = item
    if (path.split('/')[0]) {
      res.push(path)
    }
  })
  return res
}

const notFoundPage = {
  path: '*',
  redirect: '/404',
  hidden: true
}

const getDefaultState = () => {
  return {
    routes: [],
    addRoutes: [],
    buttons: []
  }
}
const state = getDefaultState

const mutations = {
  // 设置路由，过滤后的路由表存仓库
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons
  },
  // 重置路由，用于退出登录操作
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  }
}

const actions = {
  // 生成可访问路由表
  generateRoutes({ commit }, { asyncRoutes, routesMap }) {
    return new Promise(resolve => {
      const filterRoutesMap = MultidimensionalToOnedimensional(routesMap)
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, filterRoutesMap)
      accessedRoutes.push(notFoundPage) // 找不到路由或访问无权限路由跳转404，必须放在最后，因为只有找不到才会进入这个条件
      commit('SET_ROUTES', accessedRoutes)
      commit('SET_BUTTONS', getButtons(filterRoutesMap))
      resolve(accessedRoutes)
    })
  },
  // 重置路由，用于退出登录操作
  resetState({ commit }) {
    return new Promise(resolve => {
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
